package com.nisco.nio.socketchannel;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * TCP协议
 * 主要用来处理I/O
 * 可以非阻塞，多路复用
 *
 **/
public class SocketChannelTest {
    public static void main(String[] args)
        throws Exception {
        // 创建socketChannel，连接
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("localhost", 8000));

        // 检验
        System.out.println(socketChannel.isOpen());
        System.out.println(socketChannel.isConnected());
        System.out.println(socketChannel.isConnectionPending());

        // blocking
        socketChannel.configureBlocking(false);

        // 读取
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (socketChannel.read(buffer) != -1) {
            System.out.println("reading..."+buffer.position());
            buffer.flip();

            CharBuffer charBuffer = buffer.asCharBuffer();
            while (charBuffer.hasRemaining()) {
                System.out.print(charBuffer.get() + " ");
            }
            System.out.println();
            buffer.clear();
        }

        socketChannel.close();
    }

}
